﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using cn.Util;

namespace yq.ControllerBase
{
    /// <summary>
    /// 验证拦截
    /// 本拦截没有错误提示，所以只用在数据一致性验证
    /// 这很复杂--修改请联系dyq
    /// </summary>
    public class VerifyFilterAttribute: ActionFilterAttribute
    {
        /// <summary>
        /// 使用过的model缓存
        /// </summary>
        public const string KeyString = "___VerifyFilter___";

        /// <summary>
        /// 取数据Request[XXX]值
        /// </summary>
        public const string RequestDataId = "___VerifyFilter_RequestDataId___";

        public string requestDataId { get; set; }

        public Type[] vfy;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="_requestDataId">Request中对象的主键名称</param>
        /// <param name="_verifyName">验证对象的typeof，该类必须继承于Verify</param>
        public VerifyFilterAttribute(string _requestDataId,params Type[] _verifyName)
        {
            requestDataId = _requestDataId;
            vfy = _verifyName;
        }

        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            System.Web.Mvc.ControllerBase controller = filterContext.Controller;

            //保存到缓存里
            controller.ViewData[RequestDataId] = requestDataId;

            if (filterContext.HttpContext.Request[requestDataId] != null)
            {
                foreach (var verify in vfy)
                {
                    Verify _verify = (Verify)Activator.CreateInstance(verify);
                    string key = filterContext.HttpContext.Request[requestDataId];
                    var user = yq.ControllerBase.BaseController.GetCurrentUser;
                    ReturnValue<object> rv = _verify.IsVerify(key, user);

                    if (rv.Status== ReturnEnum.Yes)
                    {
                        //保存到缓存里
                        filterContext.Controller.ViewData[KeyString] = rv.Value;
                    }
                    else
                    {
                        filterContext.Result = ErrorFilterAttribute.GetError("未通过对象验证（VerifyFilter is null）","", filterContext.Controller);
                        return;
                    }
                }
            }
            else
            {
                filterContext.Result = ErrorFilterAttribute.GetError("请求数据缺失（Request is null）", "", filterContext.Controller);
            }
        }
    }

    /// <summary>
    /// 验证基础类
    /// </summary>
    public abstract class Verify
    {
        public abstract ReturnValue<object> IsVerify(string key, CurrentUser user);
    }


}